package org.jsea.meta.api.service;

import org.jsea.meta.api.bean.ApiTableInfo;
import org.jsea.meta.api.constant.ActionType;

import java.util.Map;
import java.util.function.BiFunction;

/**
 * --.
 * *
 * author   Jiang.hy
 * create   2022-04-14
 */
public class MetaApiAccessHandler {

    private final Map<String, ApiTableInfo> resource;
    public BiFunction<String, ActionType, ApiTableInfo> filtter;

    public MetaApiAccessHandler(Map<String, ApiTableInfo> resource) {
        this.resource = resource;
    }

    public ApiTableInfo getTable(String name, ActionType at) {
        return filtter.apply(name, at);
    }

    public void verifypermissions(boolean check, String primary) {
        if (check) {
            filtter = (name, at) -> {
                ApiTableInfo ti = resource.get(name);
                if (ti == null) {
                    throw new IllegalArgumentException("[" + name + "] cannot be accessed.");
                }
                if (ti.getAction().contains(at)) {
                    return ti;
                }
                throw new IllegalArgumentException("[" + name + "] cannot be " + at);
            };
        } else {
            filtter = (name, at) -> {
                ApiTableInfo ti = resource.get(name);
                if (ti == null) {
                    ti = new ApiTableInfo(name);
                    ti.setPrimaryKey(primary);
                }
                return ti;
            };
        }
    }
}
